package com.cneiu.ppms.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cneiu.ppms.web.base.BaseController;
import com.cneiu.ppms.web.model.UserModel;
import com.cneiu.ppms.web.model.UserRoleModel;
import com.cneiu.ppms.web.service.UserRoleService;
import com.cneiu.ppms.web.service.UserService;
import com.cneiu.ppms.web.validator.LoginValidator;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;

/**
 * 用户控制器
 * @author zhaokf
 * @date 2013-04-15
 */
public class UserController extends BaseController{
	
	
	/**
	 * 验证码
	 */
	public void loginVerify() {
		render("/common/image.jsp");
	}
	
	/**
	 * 用户登录
	 */
	@Before(LoginValidator.class)
	public void login(){
		UserModel users = UserService.login(getParams());
		if(users!=null){
			/**登录成功**/
			setSessionAttr("sysuser", users);
			renderAjax();
		}else{
			renderAjax(false, "登录失败，请检查用户名密码输入是否正确!");
		}
	}
	
	/**
	 * 获取登录用户的角色列表(需要登录)
	 */
	public void getLoginRoles(){
		UserModel loginUser = getSessionAttr("sysuser");
		if(null!=loginUser){
			String user_no = loginUser.getStr("USER_NO");
			Map<String,String> params = new HashMap<String,String>();
			params.put("auth_user_no", user_no);
			List<UserRoleModel> roleList = UserRoleService.get(params);
			renderGrid(roleList);
		}else{
			renderAjax(false, "您还没有登录,或者登录信息失效,请重新登录!");
		}
	}
	
	/**
	 * 获取登录用户的权限列表(需要登录)
	 */
	public void getLoginAuths(){
		UserModel loginUser = getSessionAttr("sysuser");
		if(null!=loginUser){
			String user_no = loginUser.getStr("USER_NO");
			Map<String,String> params = new HashMap<String,String>();
			params.put("auth_user_no", user_no);
			List<UserRoleModel> roleList = UserRoleService.get(params);
			renderGrid(roleList);
		}else{
			renderAjax(false, "您还没有登录,或者登录信息失效,请重新登录!");
		}
	}
	

	/**
	 * 用户列表
	 */
	public void list(){
		Page<UserModel> Users = UserService.list(this.getParams());
		if (null != Users){
			renderGrid(Users.getTotalRow(), Users.getList());
		}else{
			renderAjax(false, UserService.getError());
		}
	}

	/**
	 * 用户添加
	 */
	public void add(){
		try{
			boolean isNotError = true;
			if (!UserService.isAdd(this.getParams())){
				isNotError = false;
			}
			renderAjax(isNotError, UserService.getError());
		}
		catch (Exception e){
			e.printStackTrace();
		}

	}

	/**
	 * 用户编辑
	 */
	public void edit(){
		try{
			boolean isNotError = true;
			if (UserService.isUpdate(this.getParams())){
				isNotError = false;
			}
			renderAjax(isNotError, UserService.getError());
		}catch (Exception e){
		}
	}

	/**
	 * 用户删除
	 */
	public void delete(){
		try{
			boolean isNotError = true;
			if (UserService.isDelete(this.getParams())){
				isNotError=false;
			}
			renderAjax(isNotError, UserService.getError());
		}
		catch (Exception e){
		}
	}
}
